// pages/my-demand-edit/my-demand-edit.ts
import { getPublishDetail, editPublish } from '../../../api/publish.js'
import { getCategoryNames, getProductsByCategory, getDemandCategoryNames } from '../../../config/product-categories.js'
import { goBack } from '../../../config/pages.js'

interface FormData {
  product_category: string;
  product_name: string;
  product_model: string;
  category: string;
  remark: string;
  province: string;
  city: string;
  district: string;
  province_id: number;
  city_id: number;
  district_id: number;
  detail_address: string;
  contact_name: string;
  contact_phone: string;
  contact_email: string;
}

Page({
  data: {
    id: '',
    loading: true,
    publishType: 'demand', // 单据类型：求购
    formData: {
      product_category: '',
      product_name: '',
      product_model: '',
      category: '',
      remark: '',
      province: '',
      city: '',
      district: '',
      province_id: 0,
      city_id: 0,
      district_id: 0,
      detail_address: '',
      contact_name: '',
      contact_phone: '',
      contact_email: ''
    } as FormData,
    
    demandCategoryList: getDemandCategoryNames(),
    showDemandCategoryPicker: false,
    demandCategoryIndex: 0,
    
    categoryList: getCategoryNames(),
    showCategoryPicker: false,
    categoryIndex: 0,
    
    productList: [] as string[],
    showProductPicker: false,
    productIndex: 0,
    
    techParamsUrl: '',
    techParamsFileName: '',
    
    submitting: false
  },

  onLoad(options: any) {
    const { id } = options;
    if (id) {
      this.setData({ id });
      this.loadDetail();
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none',
      });
      setTimeout(() => {
        goBack();
      }, 1500);
    }
  },

  async loadDetail() {
    this.setData({ loading: true });

    try {
      const res = await getPublishDetail(this.data.id);

      if ((res.status === 200 || res.code === 200) && res.data) {
        const detail = res.data;
        
        // 保存单据类型
        if (detail.type) {
          this.setData({ publishType: detail.type });
        }
        
        const categoryIndex = this.data.categoryList.indexOf(detail.product_category || '');
        const productList = detail.product_category 
          ? getProductsByCategory(detail.product_category) 
          : [];
        const productIndex = productList.indexOf(detail.product_name || '');
        const demandCategoryIndex = this.data.demandCategoryList.indexOf(detail.category || '');
        
        this.setData({
          formData: {
            product_category: detail.product_category || '',
            product_name: detail.product_name || '',
            product_model: detail.product_model || '',
            category: detail.category || '',
            remark: detail.remark || '',
            province: detail.province || '',
            city: detail.city || '',
            district: detail.district || '',
            province_id: detail.province_id || 0,
            city_id: detail.city_id || 0,
            district_id: detail.district_id || 0,
            detail_address: detail.detail_address || '',
            contact_name: detail.contact_name || '',
            contact_phone: detail.contact_phone || '',
            contact_email: detail.contact_email || ''
          },
          productList: productList,
          categoryIndex: categoryIndex >= 0 ? categoryIndex : 0,
          productIndex: productIndex >= 0 ? productIndex : 0,
          demandCategoryIndex: demandCategoryIndex >= 0 ? demandCategoryIndex : 0,
          loading: false,
        });
      } else {
        wx.showToast({
          title: res.msg || '加载失败',
          icon: 'none',
        });
        this.setData({ loading: false });
      }
    } catch (error: any) {
      console.error('加载详情失败:', error);
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.message || '加载失败'),
        icon: 'none',
      });
      this.setData({ loading: false });
    }
  },

  onInputChange(e: any) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    this.setData({
      [`formData.${field}`]: value
    });
  },

  onModelInput(e: any) {
    this.setData({
      'formData.product_model': e.detail.value
    });
  },

  onRemarkInput(e: any) {
    this.setData({
      'formData.remark': e.detail.value
    });
  },

  onContactNameInput(e: any) {
    this.setData({
      'formData.contact_name': e.detail.value
    });
  },

  onContactPhoneInput(e: any) {
    this.setData({
      'formData.contact_phone': e.detail.value
    });
  },

  onEmailInput(e: any) {
    this.setData({
      'formData.contact_email': e.detail.value
    });
  },

  showDemandCategoryPicker() {
    this.setData({
      showDemandCategoryPicker: true
    });
  },

  onDemandCategoryChange(e: any) {
    const index = e.detail.value[0];
    this.setData({
      demandCategoryIndex: index
    });
  },

  onDemandCategoryCancel() {
    this.setData({
      showDemandCategoryPicker: false
    });
  },

  onDemandCategoryConfirm() {
    const index = this.data.demandCategoryIndex || 0;
    const category = this.data.demandCategoryList[index];
    this.setData({
      showDemandCategoryPicker: false,
      'formData.category': category
    });
  },

  showCategoryPicker() {
    this.setData({
      showCategoryPicker: true
    });
  },

  showProductPicker() {
    this.setData({
      showProductPicker: true
    });
  },

  onCategoryChange(e: any) {
    const index = e.detail.value[0];
    this.setData({
      categoryIndex: index
    });
  },

  onCategoryCancel() {
    this.setData({
      showCategoryPicker: false
    });
  },

  onCategoryConfirm() {
    const index = this.data.categoryIndex || 0;
    const category = this.data.categoryList[index];
    const products = getProductsByCategory(category);
    this.setData({
      showCategoryPicker: false,
      'formData.product_category': category,
      'formData.product_name': '',
      productList: products,
      productIndex: 0
    });
  },

  onProductChange(e: any) {
    const index = e.detail.value[0];
    this.setData({
      productIndex: index
    });
  },

  onProductCancel() {
    this.setData({
      showProductPicker: false
    });
  },

  onProductConfirm() {
    const index = this.data.productIndex || 0;
    const product = this.data.productList[index];
    this.setData({
      showProductPicker: false,
      'formData.product_name': product
    });
  },

  onAddressChange(e: any) {
    const { address } = e.detail;
    if (address) {
      this.setData({
        'formData.province': address.province,
        'formData.city': address.city,
        'formData.district': address.district,
        'formData.province_id': address.province_id,
        'formData.city_id': address.city_id,
        'formData.district_id': address.district_id
      });
    }
  },

  async saveEdit() {
    if (!this.validateForm()) {
      return;
    }

    this.setData({ submitting: true });

    wx.showLoading({
      title: '保存中...'
    });
    
    try {
      const submitData: any = {
        ...this.data.formData,
        type: this.data.publishType // 添加单据类型
      };
      
      if (this.data.techParamsUrl) {
        submitData.tech_params_atts = JSON.stringify([{
          url: this.data.techParamsUrl,
          name: this.data.techParamsFileName
        }]);
        submitData.tech_params_file_name = this.data.techParamsFileName;
      }

      const result = await editPublish(this.data.id, submitData);
      
      if (result.status === 200 || result.code === 200) {
        wx.hideLoading();
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });
        setTimeout(() => {
          goBack();
        }, 1500);
      } else {
        wx.hideLoading();
        wx.showToast({
          title: result.msg || '保存失败',
          icon: 'none'
        });
        this.setData({ submitting: false });
      }
    } catch (error: any) {
      console.error('保存失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.msg || '保存失败，请重试'),
        icon: 'none'
      });
      this.setData({ submitting: false });
    }
  },

  validateForm(): boolean {
    const { formData } = this.data;
    
    if (!formData.category) {
      wx.showToast({
        title: '请选择求购分类',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.product_category) {
      wx.showToast({
        title: '请选择产品类别',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.product_name) {
      wx.showToast({
        title: '请选择产品名称',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.product_model.trim()) {
      wx.showToast({
        title: '请输入产品型号',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.province) {
      wx.showToast({
        title: '请选择所在地',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.contact_name.trim()) {
      wx.showToast({
        title: '请输入联系人姓名',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.contact_phone.trim()) {
      wx.showToast({
        title: '请输入联系电话',
        icon: 'none'
      });
      return false;
    }

    return true;
  }
});

